package data

import (
	"fmt"
	"github.com/go-redis/redis/v8"
	"gorm.io/driver/mysql"
	"icasset/internal/model"

	"gorm.io/gorm"
)

var DB *gorm.DB

type DBConfig struct {
	DBUser     string
	DBPassword string
	DBHost     string
	DBPort     string
	DBName     string
}

func NewDBConfig() *DBConfig {
	return &DBConfig{
		DBUser:     "root",
		DBPassword: "root",
		DBHost:     "localhost",
		DBPort:     "3309",
		DBName:     "test",
	}
}

func InitDB() *gorm.DB {
	config := NewDBConfig()
	//dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Shanghai", config.DBHost, config.DBUser, config.DBPassword, config.DBName, config.DBPort)
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", config.DBUser, config.DBPassword, config.DBHost, config.DBPort, config.DBName)
	var err error
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}
	fmt.Println("数据库连接成功")

	// 自动迁移表结构
	err = db.AutoMigrate(&model.IcDemand{})
	if err != nil {
		panic("failed to migrate database tables")
	}
	err = db.AutoMigrate(&model.User{})
	if err != nil {
		panic("failed to migrate database tables")
	}
	fmt.Println("表结构同步完成")

	return db
}

func NewRedisConfig() *redis.Options {
	return &redis.Options{
		Addr:     "localhost:6379",
		Password: "",
		DB:       0,
	}
}
func InitRedisClient() *redis.Client {
	config := NewRedisConfig()
	return redis.NewClient(
		&redis.Options{
			Addr:     config.Addr,
			Password: config.Password,
			DB:       config.DB,
		})
}
